#include "Animation.h"

#include <iostream>

using namespace std;

Animation::Animation() {
    currentFrame    = 0;
    MaxFrames       = 0;
    k = p = 0;
    status = CA_LOOP;
    
    width = height = 0;

    FrameRate       = 100; //Milliseconds
    OldTime         = 0;
}

void Animation::OnAnimate() {
    Uint32 time = SDL_GetTicks();
    Uint32 timeElapsed = 0;
    
    if(status == CA_STOP) return;
    
    if( (Uint32)(OldTime + FrameRate) > time) {
        return;
    }

    timeElapsed = time - OldTime;
    OldTime = time;
    
    // Calculamos el numero de frames que hay que adelantar
    currentFrame += timeElapsed / FrameRate;

    if(status == CA_LOOP)
        while(currentFrame>p) currentFrame = currentFrame%(p-k+1)+k;
    else if(status == CA_ENDING && currentFrame >= MaxFrames){
        currentFrame = MaxFrames-1;
        status = CA_STOP;
    }
}

void Animation::SetFrameRate(int Rate) {
    if(Rate != 0) FrameRate = Rate;
}

void Animation::SetCurrentFrame(int Frame) {
    if(Frame < 0 || Frame >= MaxFrames) return;

    currentFrame = Frame;
}

int Animation::GetCurrentFrame() {
    return currentFrame;
}

void Animation::startAnimation(int frame, int rate){
    currentFrame = frame;
    this->SetFrameRate(rate);
    status = CA_LOOP;
}
void Animation::finishAnimation(){
    status = CA_ENDING;
}

int Animation::getX(){
    return currentFrame*width;
}

int Animation::getY(){
    return 0;
}

int Animation::getWidth(){
    return width;
}

int Animation::getHeight(){
    return height;
}
